package io;

import java.io.File;
import java.util.Scanner;

/**
 * @author haomin
 * @date 2022/06/08 16:55
 **/
public class DeleteDir {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("请输入您想要查看的文件夹名称：");
        String dir = in.nextLine();
        String path = "D:\\电影\\" + dir;

        File file = new File(path);
        if(!file.isDirectory()){
            System.out.println("您输入的不是文件夹");
            return;
        }
        queryDir(file);

        System.out.println();
        System.out.print("请输入您想删除的文件夹或文件名称：");
        String name = in.nextLine();
        deleteFile(name,file);
    }

    // 删除指定文件夹或文件
    private static void deleteFile(String name, File file) {
        File[] files = file.listFiles();
        if(files == null){
            return;
        }
        for(File file1 : files){
            if(file.isDirectory()){
                String goal = file1.getName();
                if(name.equals(goal)){
                    deleteAll(file1);
                    file1.delete();
                    System.out.println("删除文件夹成功！");
                    return;
                }

                deleteFile(name,file1);
            }else {
                String goal = file1.getName();
                if(name.equals(goal)){
                    file1.delete();
                    System.out.println("删除文件成功！");
                    return;
                }
            }
        }
    }

    // 删除该文件夹下所有内容
    private static void deleteAll(File file1) {
        File[] files = file1.listFiles();
        if(files == null){
            return;
        }

        for(File file : files){
            if(file.isFile()){
                file.delete();
            }else {
                deleteAll(file);

                file.delete();
            }
        }
    }

    // 查询文件夹内容
    private static void queryDir(File file) {
        File[] files = file.listFiles();
        if(files == null){
            return;
        }

        for(File file1 : files){
            if(file1.isDirectory()){
                String path = file1.getPath();
                System.out.println(path);

                queryDir(file1);
            }else {
                String path = file1.getPath();

                System.out.println(path);
            }
        }
    }
}